import {RemoteStorage} from "./storage";
import fs from "fs";
import logging from '../logging'
import {stat} from 'fs-extra'
import {skipUpload} from './skip'

export const UPLOAD_FILE_MAX_SIZE = 2 * 1000 * 1000 * 1000; // 2GB

export async function upload(remoteStorage: RemoteStorage, artifactFullName: string, objectKey: string, headers: object | undefined): Promise<void> {

    if (!objectKey) {
        logging.error("oss objectKey not exists, abort uploading. ")
        return ;
    }
    if (!fs.existsSync(artifactFullName)) {
        logging.error('File does not exist, abort uploading. ');
        return ;

    }

    const fileSize = fs.statSync(artifactFullName).size;
    logging.info(`${artifactFullName} size ${fileSize}`);

    if (fileSize > UPLOAD_FILE_MAX_SIZE) {
        logging.info(`${artifactFullName} size ${fileSize} exceeding max size limit ${UPLOAD_FILE_MAX_SIZE}, abort uploading.`);
        return ;
    }
    logging.info(`try to upload ${artifactFullName}`);

    let options = {};
    if(headers){
        options={headers};
    }
    const result = await remoteStorage.put(objectKey, artifactFullName, options)
    if (result.res.status == 200) {
        logging.info("upload file successfully");
    } else {
        logging.error("failed to upload file " + result.data.toString());
        return ;
    }
}


//will upload only when the local file is newer
export async function uploadWithUpdate(remoteStorage: RemoteStorage, artifactFullName: string, objectKey: string, headers: object | undefined): Promise<void> {
    if (!objectKey) {
        throw new Error("oss objectKey not exists, abort uploading. ")
    }
    if (!fs.existsSync(artifactFullName)) {
        throw new Error('File does not exist, abort uploading. ');
    }

    let options = {};
    if(headers){
        options={headers};
    }

    const artifactModifiedTime = fs.statSync(artifactFullName).mtime;

    const skip = await skipUpload(remoteStorage, objectKey, artifactModifiedTime);
    if (skip){
        logging.info(`upload file skip: ${artifactFullName}`)
        return;
    }

    const result = await remoteStorage.put(objectKey, artifactFullName, options)
    if (result.res.status == 200) {
        logging.info(`upload file ${artifactFullName} successfully`);
    } else {
        logging.error("failed to upload file " + result.data.toString());
        return ;
    }
}




